/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.order.controller.member;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.Refunds;
import com.rzico.account.model.Attach;
import com.rzico.account.service.PaymentService;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.*;
import com.rzico.basics.model.ShopVo;
import com.rzico.basics.service.*;
import com.rzico.core.entity.*;
import com.rzico.core.service.*;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.*;
import com.rzico.order.model.ShippingEmloyeeVo;
import com.rzico.order.plugin.JDPluginService;
import com.rzico.order.service.*;
import com.rzico.basics.service.CouponCodeService;
import com.rzico.util.MD5Utils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.JRException;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;

/**
 * 销售单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "销售单接口")
@RestController
@RequestMapping("/member/order")
public class OrderController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired @Lazy
    private MsgService msgService;

    @Autowired
    private SysSequenceService sysSequenceService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CartService cartService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private ReceiverService receiverService;

    @Autowired
    private CartItemService cartItemService;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderPlanService orderPlanService;

    @Autowired
    private OrderLogService orderLogService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private SysEmployeeService sysEmployeeService;

    @Autowired
    private AskforService askforService;

    @Autowired
    private ShippingService shippingService;

    @Autowired
    private OrderPromotionService orderPromotionService;

    @Autowired
    private CouponCodeService couponCodeService;

    @Autowired
    private MapLineService mapLineService;

    @Autowired
    private GiftCardService giftCardService;

    @Autowired
    private GroupBuyService groupBuyService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private JDPluginService jDPluginService;

    @Autowired
    private ShippingItemService shippingItemService;


    /**
     * 分页查询销售单
     *
     * @return
    */
    @ApiOperation("分页查询销售单")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderStatus", value = "订单状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "paymentStatus", value = "付款状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "shippingStatus", value = "配送状态", dataType = "Integer", paramType = "query")
    })
    public CommResult<Order> list(Integer orderStatus,
                                  Integer paymentStatus, Integer shippingStatus, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();

        params = buildSortField(params, pageable);
        if (null != orderStatus){
            params.put("orderStatus", orderStatus);
        }
        if (null != paymentStatus){
            params.put("paymentStatus", paymentStatus);
        }
        if (null != shippingStatus){
            params.put("shippingStatus", shippingStatus);
        }

        params.put("deleted", 0);
        Member member = memberService.getCurrent();
        if (member!=null) {
            params.put("memberId", member.getId());
        } else {
            return CommResult.error("没有登录");
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Order> list = orderService.selectList(params);
        PageResult<Order> pageResult = new PageResult<Order>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条销售单
     *
     * @return
    */
    @ApiOperation("查询单条销售单")
    @GetMapping("/find/{id}")
    public CommResult<Order> find(@PathVariable Long id) {

        Order result = orderService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("order",result);
        result.setItemList(orderItemService.getItemList(result.getId()));

        data.put("bomType",orderService.checkBomType(result));


        Map<String,Object> paymentParams = new HashMap<>();
        paymentParams.put("orderType",0);
        paymentParams.put("orderId",id);
        paymentParams.put("success",1);
        data.put("payments",paymentService.selectList(paymentParams));


        data.put("promotions",orderPromotionService.getPromotions(id));
        Map<String,Object> params = new HashMap<>();
        params.put("orderId",id);
        params.put("sortField","id");
        params.put("sortType","desc");
        data.put("orderLog",orderLogService.selectList(params));


        if (result.getCouponCodeId()!=null) {
            CouponCode couponCode = couponCodeService.findById(result.getCouponCodeId());
            if (couponCode!=null) {
                data.put("couponCodeName",couponCode.getCoupon().getName());
            }
        }

        params.clear();
        params.put("orderId", id);
        List<Shipping> shippingList = shippingService.selectList(params);

        List<ShippingEmloyeeVo> shippingEmloyeeVoList = new ArrayList<>();
        for (Shipping rn : shippingList) {
            if (rn.getShippingEmployeeId() != null) {
                ShippingEmloyeeVo vo = new ShippingEmloyeeVo();
                SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(rn.getShippingEmployeeId());
                if (sysEmployee != null) {
                    vo.setMobile(sysEmployee.getPhone());
                    vo.setName(sysEmployee.getName());
                    shippingEmloyeeVoList.add(vo);
                }

            }
        }
        data.put("shippingEmloyeeList",shippingEmloyeeVoList);

        if (result.getShopId()!=null) {
            Shop shop = shopService.selectByPrimaryKey(result.getShopId());
            if (shop!=null) {
                data.put("shopName",shop.getName());
                data.put("telephone",shop.getTelephone());

            }
        }

        return CommResult.success(data);

    }

    /**
     * 创建订单
     *
     * @param order
     * @return
     */
    @ApiOperation("创建订单")
    @PostMapping("/create")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "用户ID", dataType = "Integer", paramType = "query")
    })
    public CommResult<Order> create(@RequestBody Order order,String uuid) {

        logger.info(">>>>>>>>>>>>>>>>保存订单 start <<<<<<<<<<<<<<<<<");
        logger.info("保存订单参数：[{}]", order.toString());
        Assert.notNull(order, "订单参数为空");
        Assert.notNull(order.getItemList(), "请选购商品");

        if (order.getGiftCardId()!=null) {
            GiftCard giftCard = giftCardService.selectByPrimaryKey(order.getGiftCardId());
            if (giftCard==null) {
                return CommResult.error("无效礼卡ID");
            }
            if (giftCard.getStatus().equals(2)) {
                return CommResult.error("礼卡已使用");
            }
        }


        if (order.getGroupBuyId()!=null) {
            GroupBuy groupBuy = groupBuyService.selectByPrimaryKey(order.getGroupBuyId());
            if (groupBuy.getBuyNum()>=groupBuy.getGroupNum()) {
                return CommResult.error("团购已结束");
            }
            if (groupBuy==null) {
                return CommResult.error("无效团购ID");
            }
            if (!groupBuy.getStatus().equals(1)) {
                return CommResult.error("团购已结束");
            }
        }


        if (order.getReceiverId()==null && (order.getShippingMethod()!=1)) {
            return CommResult.error("请正确选择收货地址");
        }
        if (order.getShopId()==null && (order.getShippingMethod()==1)) {
            return CommResult.error("请正确选择提货门店");
        }

        Member member = memberService.getCurrent();
        if (member==null) {
            return CommResult.error("没有登录");
        }

        //检查限购数量
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",member.getId());
        params.put("startDate",DateUtils.truncate(new Date(),Calendar.DATE));
        params.put("endDate",DateUtils.addDays(DateUtils.truncate(new Date(),Calendar.DATE),1));
        for (OrderItem orderItem:order.getItemList()) {
            Product product = productService.selectByPrimaryKey(orderItem.getProductId());
            if (product.getMaxLimit()>0) {
                params.put("productId",orderItem.getProductId());
                BigDecimal q = orderItemService.checkSumProduct(params);
                q = q.add(orderItem.getQuantity());
                if (q.compareTo(new BigDecimal(product.getMaxLimit()))>0) {
                    return CommResult.error("超出限购量");
                }
            }
        }

        order.setSn(sysSequenceService.generate("order"));

        try {
            int affectCount = orderService.insertOrder(order);
            if (affectCount <= 0) {
                return CommResult.error();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return CommResult.error(e.getMessage());
        }

        //删除购物车
        Order result = orderService.findById(order.getId());
        result.setItemList(orderItemService.getItemList(result.getId()));

        Cart cart = cartService.getCurrent(member,uuid);
        if (cart!=null) {
            cart.setItemList(cartItemService.getItemList(cart.getId()));
            for (OrderItem orderItem:result.getItemList()) {
               CartItem cartItem = cart.findItem(orderItem.getProductId());
               if (cartItem!=null) {
                   cartItemService.delete(cartItem);
               }
            }
        }

        logger.info(">>>>>>>>>>>>>>>>保存订单 end <<<<<<<<<<<<<<<<<");

        return CommResult.success(result);

    }


    /**
     * 订单付款
     *
     * @param id
     * @return
     */
    @ApiOperation("订单付款")
    @PostMapping("/payment/{id}")
    public CommResult<Order> payment(@PathVariable Long id) {
        Order order = orderService.findById(id);
        if (order==null) {
            return CommResult.error("无效付款单号");
        }
        if (order.getCreateDate().before(DateUtils.addMinutes(new Date(),-28))) {
            return CommResult.error("超时订单不能付款");
        }
        String sn = sysSequenceService.generate("payment");
        System.out.println("=====sn");
        Payment payment = orderService.payment(order,sn);
        System.out.println("=====payment end");
        return CommResult.success(payment);
    }

    /**
     * 批量删除销售单
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除销售单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除销售单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Order> del(@PathVariable String ids) {

        orderService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 修改收货地址
     *
     * @param order
     * @return
     */
    @ApiOperation("修改收货地址")
    @PostMapping("/update")
    public CommResult<Order> update(@RequestBody Order order) {
        int affectCount = orderService.updateByPrimaryKeySelective(order);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Order result = orderService.findById(order.getId());
        logger.info(">>>>>>>>>>>>>>>>订单编辑 end <<<<<<<<<<<<<<<<<");
        return CommResult.success(result);
    }

    /**
     * 购物车生成订单
     *
     * @param uuid
     * @return
     */
    @ApiOperation("购物车生成订单")
    @GetMapping("/build")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "用户ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "giftCardId", value = "来源礼卡", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "groupBuyId", value = "团购ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "bargainBuyId", value = "砍价ID", dataType = "Long", paramType = "query")
    })
    public CommResult<Order> build(String uuid,Long giftCardId,Long groupBuyId,Long bargainBuyId) {
        Member member = memberService.getCurrent();
        if (member==null) {
            return CommResult.error("没有登录");
        }
        Order order = null;
        if (giftCardId==null) {
            Cart cart = cartService.getCurrent(member, uuid);
            if (cart != null) {
                cart.setItemList(cartItemService.getItemList(cart.getId()));

                if (cart.getItemList().size() == 0) {
                    return CommResult.error("没有选择商品");
                }

            } else {
                return CommResult.error("没有选择商品");
            }
            order = orderService.build(cart);
            order.setGroupBuyId(groupBuyId);
            order.setBargainBuyId(bargainBuyId);
        } else {
            GiftCard giftCard = giftCardService.selectByPrimaryKey(giftCardId);
            order = giftCardService.build(giftCard);
        }
        order = orderService.calculate(order);


        order.setPaymentVo(orderService.calculatePayment(order));

        Map<String,Object> data = new HashMap<>();
        data.put("order",order);
        data.put("shippingMethods",orderService.getShippingMethods(order));
        data.put("amount",order.getAmountPayable().subtract(order.calculatePaymentPaid()));

        if (order.getCouponCodeId()!=null) {
            CouponCode couponCode = couponCodeService.findById(order.getCouponCodeId());
            if (couponCode!=null) {
                data.put("couponCodeName",couponCode.getCoupon().getName());
            }
        }

        return CommResult.success(data);
    }


    /**
     * 检查是否能配送
     *
     * @param order
     * @return
     */
    @ApiOperation("检查是否能配送")
    @PostMapping("/check_shipping")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "receiverId", value = "收货地址", dataType = "Integer", paramType = "query")
    })
    public CommResult<OrderItem> checkShipping(@RequestBody Order order,Long receiverId) {

        //同城配送时，检查围拦可配送区域
        if (order.getShippingMethod()==2) {
            //同城商品，查看是否
            Receiver receiver = receiverService.findById(receiverId);
            if (receiver.getLng()==null || receiver.getLat()==null ) {
                return CommResult.error("超出配送范围");
            }

            for (OrderItem orderItem : order.getItemList()) {
                Product product = productService.selectByPrimaryKey(orderItem.getProductId());
                Enterprise enterprise = enterpriseService.findById(product.getEnterpriseId());
                MapLine mapLine = mapLineService.findByPoint(enterprise,null,receiver.getLat(), receiver.getLng());
                if (mapLine==null) {
                    return CommResult.error("超出配送范围");
                }
            }

        }
        List<OrderItem> shippings = new ArrayList<>();

        //到店自提时，检查不能提货的商品
        if (order.getShippingMethod()==1) {

            Shop shop = shopService.selectByPrimaryKey(order.getShopId());
            if (shop==null) {
                return CommResult.error("请选择提货门店");
            }

            if (shop.getSupplierId()!=null) {
                for (OrderItem orderItem : order.getItemList()) {
                    Product product = productService.selectByPrimaryKey(orderItem.getProductId());
                    if (!shop.getSupplierId().equals(product.getSupplierId())) {
                        //不能送的商品
                        shippings.add(orderItem);
                    }
                }
            }

        }

        for (OrderItem orderItem : order.getItemList()) {
            Product product = productService.selectByPrimaryKey(orderItem.getProductId());
            //订单提交前库存检查
            if (new BigDecimal(product.getStock()).compareTo(orderItem.getQuantity()) < 0) {
                shippings.add(orderItem);
                return CommResult.error("商品:" + product.getName() + "库存不足");
            }
            if (product.getShippingMethod() == null) {
                product.setShippingMethod("0");
            }
            if (product.getShippingMethod().indexOf(String.valueOf(order.getShippingMethod())) < 0) {
                //不能送的商品
                shippings.add(orderItem);
            }
        }

        /**
         * 判断订单中提交的商品是否有京东商品，并对之进行校验
         */
        Member member = memberService.getCurrent();
        if (member==null) {
            return CommResult.error("没有登录");
        }
        Map<String,Object> result = jDPluginService.checkJDPruduct(order, member.getEnterpriseId(), member.getMchId());
        if (result.get("returnCode").equals("0001")) {
            return CommResult.error(result.get("returnMsg").toString());
        }
        return CommResult.success(shippings);
    }


    /**
     * 获取提货二维码
     *
     * @param orderId
     * @return
     */
    @ApiOperation("获取提货二维码")
    @GetMapping("/pickup_qrcode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID", dataType = "Integer", paramType = "query")
    })
    public CommResult<OrderItem> pickupQrcode(Long orderId) {

        Order order = orderService.findById(orderId);
        if (order==null) {
            return CommResult.error("无效订单号");
        }

        String qrcodeData = "od" + order.getSn()+ MD5Utils.getMD5Str("od" + order.getSn()+order.getId());

        return CommResult.success(qrcodeData);
    }


    /**
     * 获取订单提货门店
     *
     * @param order
     * @return
     */
    @ApiOperation("获取订单提货门店")
    @PostMapping("/shopList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lat", value = "lat", dataType = "Double", paramType = "query"),
            @ApiImplicitParam(name = "lng", value = "lng", dataType = "Double", paramType = "query"),
    })
    public CommResult<Shop> shopList(@RequestBody Order order,Double lat,Double lng) {
        Map<String, Object> params = new HashMap<String, Object>();

        Enterprise enterprise = enterpriseService.selectByPrimaryKey(order.getEnterpriseId());
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        Long supplierId = null;
        for (OrderItem orderItem:order.getItemList()) {
            Product product = productService.selectByPrimaryKey(orderItem.getProductId());
            if (product.getShippingMethod()==null) {
                product.setShippingMethod("0");
            }
            if (product.getShippingMethod().indexOf("1")>=0) {
                supplierId = product.getSupplierId();
                break;
            }
        }

        if (supplierId!=null) {
            params.put("supplierId", supplierId);
        }

        List<ShopVo> list = shopService.selectLbsList(params,lat,lng);
        return CommResult.success(list);


    }

        /**
         * 计算订单金额
         *
         * @param order
         * @return
         */
    @ApiOperation("计算订单金额")
    @PostMapping("/calculate")
    public CommResult<Order> calculate(@RequestBody Order order) {
        order.setPromotions(new ArrayList<OrderPromotion>());
        Order result = orderService.calculate(order);
        Map<String,Object> data = new HashMap<>();
        data.put("order",result);

        result.setPaymentVo(orderService.calculatePayment(order));

        if (result.getCouponCodeId()!=null) {
            CouponCode couponCode = couponCodeService.findById(result.getCouponCodeId());
            if (couponCode!=null) {
                data.put("couponCodeName",couponCode.getCoupon().getName());
            }
        }

        data.put("bomType",orderService.checkBomType(result));

        data.put("matchPoint",orderService.calculatePoint(result));

        data.put("amount",order.getAmountPayable().subtract(order.calculatePaymentPaid()));
        return CommResult.success(data);
    }

    /**
     * 统计末完成订单数
     *
     * @return
     */
    @ApiOperation("统计末完成订单数")
    @PostMapping("/summary")
    public CommResult<Order> summary() {

        Member member = memberService.getCurrent();

        Map<String,Object> data = new HashMap<>();
        Map<String,Object> params = new HashMap<>();

        params.put("orderStatus",0);
        params.put("paymentStatus",0);
        params.put("shippingStatus",0);
        params.put("memberId",member.getId());
        params.put("deleted",false);
        data.put("unpaid",orderService.selectRowCount(params));

        params.clear();
        params.put("orderStatus",1);
        params.put("shippingStatus",0);
        params.put("paymentStatus",1);
        params.put("memberId",member.getId());
        params.put("deleted",false);
        data.put("unshipping",orderService.selectRowCount(params));

        params.clear();
        params.put("orderStatus",1);
        params.put("shippingStatus",1);
        params.put("paymentStatus",1);
        params.put("memberId",member.getId());
        params.put("deleted",false);
        data.put("shipped",orderService.selectRowCount(params));

        params.clear();
        params.put("shippingStatus",1);
        params.put("paymentStatus",1);
        params.put("orderStatus",2);
        params.put("memberId",member.getId());
        params.put("deleted",false);
        data.put("completed",orderService.selectRowCount(params));

        params.clear();
        params.put("askforing",1);
        params.put("memberId",member.getId());
        params.put("deleted",false);
        data.put("refunds",askforService.selectRowCount(params));

        return CommResult.success(data);

    }

    /**
     * 确认收货
     *
     * @param id
     * @return
     */
    @ApiOperation("确认收货")
    @PostMapping("/received/{id}")
    public CommResult<Order> received(@PathVariable Long id) {

        Order order = orderService.selectByPrimaryKey(id);

        if (order.getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_COMPLETE.getId()) ||
                order.getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_REVIEWED.getId())
                ) {
            return CommResult.error("订单已完成");
        }

        //检查是否退货中
        Map<String,Object> params = new HashMap<>();
        params.put("orderId",id);

        List<Askfor> askforList = askforService.selectList(params);
        for (Askfor rn:askforList) {
            if (!rn.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_COMPLETE.getId())
                    &&
                !rn.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_CANCLEED.getId())
               ) {
                return CommResult.error("退货未完成");
            }
        }


        //检查是否退货中
        if (order.getShippingMethod().equals(2)) {
            params.clear();
            params.put("orderId", id);
            List<Shipping> shippingList = shippingService.selectList(params);
            for (Shipping rn : shippingList) {
                if (rn.getShippingStatus().equals(ShippingStatusEnum.SHIPPING_STATUS_SEND.getId())
                        ||
                        rn.getShippingStatus().equals(ShippingStatusEnum.SHIPPING_STATUS_DISPATCH.getId())
                        ||
                        rn.getShippingStatus().equals(ShippingStatusEnum.SHIPPING_STATUS_UNCONFIRM.getId())
                ) {
                    return CommResult.error("订单配送中");
                }
            }

        }

        params.clear();
        params.put("orderId",id);
        params.put("status",0);
        Integer w = orderPlanService.selectRowCount(params);
        if (w>0) {
            return CommResult.error("配送没有完成");
        }

        int affectCount = orderService.received(id,false);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Order result = orderService.findById(id);
        return CommResult.success(result);

    }


    /**
     * 提醒卖家发货
     *
     * @param id
     * @return
     */
    @ApiOperation("提醒卖家发货")
    @PostMapping("/reminder/{id}")
    public CommResult<Order> reminder(@PathVariable Long id) {
        Order order = orderService.findById(id);
        if (order==null) {
            return CommResult.error("无效订单号");
        }

        Enterprise enterprise = enterpriseService.findById(order.getEnterpriseId());

        SysMch sysMch = sysMchService.findById(enterprise.getMchId());
        if (sysMch==null) {
            return CommResult.error("无效商户号");
        }

        Shipping shipping = new Shipping();
        shipping.setEnterpriseId(order.getEnterpriseId());
        shipping.setOrderId(order.getId());

        List<Shipping> shippingList = shippingService.select(shipping);
        if (shippingList.size()==0) {

            order.setItemList(orderItemService.getItemList(id));
            Map<String,Object> content = new HashMap<>();
            content.put("title","客户催单了,请尽快处理");
            content.put("itemList",order.getItemList());
            content.put("sn",order.getSn());
            content.put("id",order.getId());

           Map<String,Object> params = new HashMap<>();
            params.put("mchId",enterprise.getMchId());
            params.put("userType",1);
            List<SysUser> sysUserList = sysUserService.selectList(params);
            for (SysUser sysUser:sysUserList) {
                Boolean hasAudit = false;
                List<SysMenu> list = sysUser.getMenuList();
                for (SysMenu menu : list) {
                    if (menu.getPermission()!=null && menu.getPermission().equals("order.audit")) {
                        hasAudit = true;
                        break;
                    }
                }
                if (hasAudit) {
                    msgService.sendNotity(sysUser, "msg-order", "客户催单了,请尽快处理", JSON.toJSONString(content), "h2");
                }
            }

        } else {
            for (Shipping s:shippingList) {

                s.setItemList(shippingItemService.getItemList(s.getId()));
                Map<String, Object> contentSucc = new HashMap<>();
                contentSucc.put("title", "送货单已驳回");
                contentSucc.put("itemList", s.getItemList());
                contentSucc.put("sn", s.getOrderSn());
                contentSucc.put("id", s.getOrderId());
                contentSucc.put("shippingId", s.getId());

                if (s.getShippingEmployeeId()==null) {
                    //向店长推送
                    Shop shop = shopService.selectByPrimaryKey(s.getShopId());
                    if (shop!=null) {
                        SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(shop.getManagerId());
                        if (sysEmployee != null) {
                            SysUser sysUser = sysUserService.selectByPrimaryKey(sysEmployee.getUserId());
                            if (sysUser != null) {
                                msgService.sendNotity(sysUser, "msg-shipping", "客户催单了,请尽快处理", JSON.toJSONString(contentSucc), "h2");
                            }
                        }
                    }
                } else {
                    //向送货员推送
                    SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(s.getShippingEmployeeId());
                    if (sysEmployee != null) {
                        SysUser sysUser = sysUserService.selectByPrimaryKey(sysEmployee.getUserId());
                        if (sysUser != null) {
                            msgService.sendNotity(sysUser, "msg-shipping", "客户催单了,请尽快处理", JSON.toJSONString(contentSucc), "h2");
                        }
                    }
                }
            }
        }

        return CommResult.success("已提醒发货");
    }

    /**
     * 关闭订单
     *
     * @param id
     * @return
     */
    @ApiOperation("关闭订单")
    @PostMapping("/cancel/{id}")
    public CommResult<Order> cancel(@PathVariable Long id) {
        Order order = orderService.selectByPrimaryKey(id);
        if (!order.getPaymentStatus().equals(OrderPaymentStatusEnum.PAYMENT_STATUS_UNPAY.getId())){
            return CommResult.error("已付款不能关闭");
        }
        if (order.getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CANCLE.getId())){
            return CommResult.error("订单已关闭");
        }
        List<Refunds> refundsList = orderService.cancel(id,sysSequenceService.generate("refunds"));
        for (Refunds refunds:refundsList) {
            //TODO发送退款通知
            //TODO发送退款通知
            Attach attachQueue = new Attach();
            attachQueue.setCode("0000");
            attachQueue.setId(String.valueOf(refunds.getId()));
            attachQueue.setQueue("queue.refunds.submit");
            Message message = MessageBuilder
                    .withBody(JSON.toJSONString(attachQueue).getBytes())
                    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                    .build();
            CorrelationData correlationData = new CorrelationData();
            correlationData.setId(UUID.randomUUID().toString());
            logger.info("发送 MQ");
            rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);
        }
        Order result = orderService.findById(id);
        return CommResult.success(result);
    }

    /**
     * 我推广的订单
     *
     * @return
     */
    @ApiOperation("我推广的订单")
    @GetMapping("/orderList")
    public CommResult<Order> orderList(Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        Member member = memberService.getCurrent();
        params.put("promoterId1", member.getId());

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Order> list = orderService.selectList(params);
        PageResult<Order> pageResult = new PageResult<Order>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

}
